package com.atguigu.champter7.state;

import com.atguigu.beans.WaterSensor;
import com.atguigu.utils.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Properties;

public class Flink12_Kafka_Flink_Kafka {
    public static void main(String[] args) {
        System.setProperty("HADOOP_USER_NAME","atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env.enableCheckpointing(3000);

        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:9820/ck99");
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);

        // 确认 checkpoints 之间的时间会进行 500 ms
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);

        // Checkpoint 必须在一分钟内完成，否则就会被抛弃
        env.getCheckpointConfig().setCheckpointTimeout(60000);

        // 同一时间只允许一个 checkpoint 进行
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);

        // 开启在 job 中止后仍然保留的 externalized checkpoints
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);


        Properties sourceConfig = new Properties();
        sourceConfig.put("bootstrap.servers","hadoop102:9092,hadoop103:9092,hadoop104:9092");
        sourceConfig.put("group.id","Flink12_Kafka_Flink_Kafka");
        sourceConfig.put("auto.offset.reset","latest");
        sourceConfig.put("isolation.level","read_committed");//隔离策略,防止kafka将未提交的数据消费

        Properties sinkConfig = new Properties();
        sinkConfig.put("bootstrap.servers", "hadoop102:9092,hadoop103:9092,hadoop104:9092");
        sinkConfig.put("transaction.timeout.ms", 15 * 60 * 1000);//超时时间,要小于flink事务的最大时间[ 默认为15min ]

        SingleOutputStreamOperator<Tuple2<String, Long>> stream = env
                .addSource(new FlinkKafkaConsumer<String>("s1", new SimpleStringSchema(), sourceConfig))
                .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                        for (String word : value.split(" ")) {
                            out.collect(Tuple2.of(word, 1L));

                        }
                    }
                })
                .keyBy(t -> t.f0)
                .sum(1);
        //要实现严格一次,必须使用带语义的FlinkKafkaProducer方法
        stream.addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
                "null",//序列化器未指定topic,使用的默认topic
                new KafkaSerializationSchema<Tuple2<String, Long>>() {
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(Tuple2<String,
                            Long> ele, @Nullable Long aLong) {
                        return new ProducerRecord<byte[], byte[]>("s2",(ele.f0 + "_"+ ele.f1).getBytes(StandardCharsets.UTF_8));
                    }
                },
                sinkConfig,
                FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        ));


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
